﻿using System;
using System.Collections.Generic;
using System.Linq;
using DevExpress.XtraBars.Docking2010.Views.WindowsUI;
using DevExpress.XtraEditors;
using EduFormManager.Models;
using EduFormManager.Models.Repo;

namespace EduFormManager.Utils
{
    public static class LevelAdminHelper
    {
        public static TileContainer CreateEduFormsTileContainer(WindowsUIView view, AllformType.Type.Types formType, bool isArchive = false)
        {
            string munitCaption = "Муниципалитеты";
            string munitSubCaption = isArchive ? "Архивные " : "";
            munitSubCaption += (formType == AllformType.Type.Types.Federal) ? "Формы федерального статистического наблюдения" : "Доп. формы";

            TileContainer munitContainer = TileContainerHelper.CreateTileContainer(view, null, munitCaption, munitSubCaption);

            IList<SummaryView> summaryViewList = RepoHelper.Repo.GetSummary(isArchive);
            IList<EduFormData> dataList = RepoHelper.Repo.GetEduFormData(formType, isArchive);
            var grp = summaryViewList.GroupBy(x => new { x.EduKind, x.Municipality }).GroupBy(y => y.Key.Municipality);

            foreach (var g in grp)
            {
                Municipality m = g.Key;
                Tile mTile = TileHelper.CreateMunitTile(m, isArchive);

                munitContainer.Items.Add(mTile);

                String typeCaption = "Типы образовательных учреждений";
                String typeSubCaption = m.Name;
                TileContainer typeContainer = TileContainerHelper.CreateTileContainer(view, mTile, typeCaption, typeSubCaption, munitContainer);

                foreach (var gg in g)
                {
                    EduOrgKind eok = gg.Key.EduKind;
                    Tile eotTile = TileHelper.CreateEduTypeTile(eok, mTile, isArchive);

                    typeContainer.Items.Add(eotTile);

                    String eduCaption = "Образовательные учреждения";
                    String subEduCaption = eok.KindName;
                    TileContainer eduContainer = TileContainerHelper.CreateTileContainer(view, eotTile, eduCaption, subEduCaption, typeContainer);

                    foreach (var ggg in gg.OrderBy(x => x.Edu.ShortName))
                    {
                        EduOrg eo = ggg.Edu;
                        if (eo.Kind.Id != eok.Id)
                            continue;
                        IList<EduFormData> data = dataList.Where(x => x.EduOrg.Id == eo.Id).ToList();
                        Tile eoTile = data.Count > 0 ? TileHelper.CreateAnimatedEduTile(eo, isArchive) : TileHelper.CreateEduTile(eo, isArchive);
                        eoTile.Group = eo.ShortName.Substring(0, 1);

                        eduContainer.Items.Add(eoTile);

                        string formCaption = eo.ShortName;
                        string formSubCaption = isArchive ? "Архивные " : "";
                        formSubCaption += (formType == AllformType.Type.Types.Federal) ? "Формы федерального статистического наблюдения" : "Доп. формы";

                        TileContainer formContainer = TileContainerHelper.CreateTileContainer(view, eoTile, formCaption, formSubCaption, eduContainer);
                        formContainer.Tag = TagHelper.GetFormContainerTag(eo, formType, isArchive); //Для добавления плитки с загруженной формой
                        TileContainerHelper.InitFormContainerActions(formContainer);
                        GuiHelper.FormStatusCount statusCount = new GuiHelper.FormStatusCount() { FormsOkCount = 0, FormsWithErrorsCount = 0, FormsWithExpiredDateCount = 0, FormsWithBothCount = 0 };

                        if (data.Count > 0)
                        {
                            foreach (EduFormData fd in data)
                            {
                                Tile dTile = TileHelper.CreateFormTile(fd, view, formContainer, isArchive);
                                TileHelper.SetFormTileStatus(dTile, eoTile, eotTile, mTile, fd, ref statusCount);
                                formContainer.Items.Add(dTile);
                            }
                            eoTile.Frames[1].Elements[0].Text = String.Format(
                              "Загруженных форм {0}\nС ошибками {1}\nС опозданием {2}\nС ошибками и опозданием {3}\nБез ошибок и опозданий {4}",
                              data.Count, statusCount.FormsWithErrorsCount, statusCount.FormsWithExpiredDateCount, statusCount.FormsWithBothCount, statusCount.FormsOkCount);
                        }
                        view.ContentContainers.Add(formContainer);
                    }
                    view.ContentContainers.Add(eduContainer);
                }
                view.ContentContainers.Add(typeContainer);
            }
            view.ContentContainers.Add(munitContainer);
            return munitContainer;
        }

        public static TileContainer CreateMunicipalityFormsTileContainer(WindowsUIView view, bool isArchive = false)
        {
            string munitCaption = "Муниципалитеты";
            string munitSubCaption = isArchive ? "Архивные формы муниципалитетов" : "Формы муниципалитетов";
            TileContainer munitContainer = TileContainerHelper.CreateTileContainer(view, null, munitCaption, munitSubCaption);

            IList<Municipality> munitList = RepoHelper.Repo.GetAll<Municipality>().OrderBy((t) => t.Name).ToList();
            IList<MunicipalityFormData> dataList = RepoHelper.Repo.GetMunitFormData(isArchive);
            foreach (Municipality munit in munitList)
            {
                Tile mTile = TileHelper.CreateMunitTileForMunicipality(munit, isArchive);

                munitContainer.Items.Add(mTile);

                String formCaption = munit.Name;
                String formSubCaption = "Формы муниципалитета";

                TileContainer formContainer = TileContainerHelper.CreateTileContainer(view, mTile, formCaption, formSubCaption, munitContainer);
                formContainer.Tag = TagHelper.GetFormContainerTag(munit, AllformType.Type.Types.Municipality, isArchive); //Для добавления плитки с загруженной формой
                TileContainerHelper.InitFormContainerActions(formContainer);
                GuiHelper.FormStatusCount statusCount = new GuiHelper.FormStatusCount() { FormsOkCount = 0, FormsWithErrorsCount = 0, FormsWithExpiredDateCount = 0, FormsWithBothCount = 0 };

                IList<MunicipalityFormData> data = dataList.Where(x => x.Municipality.Id == munit.Id).ToList();
                if (data.Count > 0)
                {
                    foreach (MunicipalityFormData fd in data)
                    {
                        Tile dTile = TileHelper.CreateFormTile(fd, view, formContainer, isArchive);
                        TileHelper.SetFormTileStatus(dTile, null, null, mTile, fd, ref statusCount);
                        formContainer.Items.Add(dTile);
                    }
                    
                    mTile.Elements[1].TextAlignment = TileItemContentAlignment.BottomLeft;
                    mTile.Elements[1].Text = String.Format(
                        "Загруженных форм {0}\nС ошибками {1}\nС опозданием {2}\nС ошибками и опозданием {3}\nБез ошибок и опозданий {4}",
                        data.Count, statusCount.FormsWithErrorsCount, statusCount.FormsWithExpiredDateCount, statusCount.FormsWithBothCount, statusCount.FormsOkCount);
                }
                view.ContentContainers.Add(formContainer);
            }
            view.ContentContainers.Add(munitContainer);
            return munitContainer;
        }

        public static TileContainer CreateQuestionaryTileContainer(WindowsUIView view)
        {
            const string caption = "Анкеты";
            TileContainer questionaryContainer = TileContainerHelper.CreateTileContainer(view, null, caption);
            
            IList<Questionary> questionaryList = RepoHelper.Repo.GetAll<Questionary>().OrderBy((t) => t.Title).ToList();
            foreach (Questionary questionary in questionaryList)
            {
                Tile qTile = TileHelper.CreateQuestionaryTile(questionary, view, questionaryContainer);
                questionaryContainer.Items.Add(qTile);
            }
            view.ContentContainers.Add(questionaryContainer);
            GuiHelper.GuiThreadContext.Post(x => TileContainerHelper.InitQuestionaryContainerActions(questionaryContainer), null);
            return questionaryContainer;
        }
    }
}
